﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Meqs.Entity;
using System.Web.Services;
using Meqs.Logic.Interface;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Reflection;
using NPOI.HSSF.Util;



public partial class School_Manage_InputScore_inputscore : System.Web.UI.Page
{
    /// <summary>
    /// 考试号
    /// </summary>
    protected int examid = 0;
    /// <summary>
    /// 是否为统考 -1错误，1是，0不是
    /// </summary>
    protected int eexam = -1;
    /// <summary>
    /// 班级分科
    /// </summary>
    protected int classType = -1;
    /// <summary>
    /// 班级id
    /// </summary>
    protected int classId = 0;
    /// <summary>
    /// 班级名
    /// </summary>
    protected string clsname="";
    /// <summary>
    /// 年级
    /// </summary>
    protected int Grade = 0;

    /// <summary>
    /// 本次考试的科目(统考)
    /// </summary>
    protected IList<ExamSubjecyEducation2> subjEdu = null;
    /// <summary>
    /// 本次考试的科目(校考)
    /// </summary>
    protected IList<ExamSubjecySchool2> subjSchool = null;
    /// <summary>
    /// 学生列表信息
    /// </summary>
    protected IList<StudentInfo> studentInfo = null;
    /// <summary>
    /// 统考成绩列表（已经输入的）
    /// </summary>
    protected IList<GradeScoreEducation> gse = null;
    /// <summary>
    /// 校考试成绩
    /// </summary>
    protected IList<ExamDetailSchool> eds = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string iseexam = Request.QueryString["eexam"];
            string id = Request.QueryString["examid"];
            string ct = Request.QueryString["classtype"];
            string cid = Request.QueryString["classid"];
            string g = Request.QueryString["grade"];
            //string iseexam = "1";
            //string id = "1";
            int temp = 0;
            if (int.TryParse(id, out temp))
            {
                examid = temp;
            }

            temp = -1;
            if (int.TryParse(iseexam, out temp))
            {
                eexam = temp;
            }
            temp = -1;
            if (int.TryParse(ct, out temp))
            {
                classType = temp;
            }
            temp = 0;
            if (int.TryParse(cid, out temp))
            {
                classId = temp;
                ClsInfo tcl = Container<Meqs.Logic.Interface.IClsInfoLogic>.Instance.FindById(classId);
                clsname = tcl.ClsName;
            }
            temp = 0;
            if (int.TryParse(g, out temp))
            {
                Grade = temp;
            }
            if (eexam != -1 && examid != 0 && classType!=-1)
            {
                Hashtable table = new Hashtable();
                table.Add("ClsID", classId);
                table.Add("IsEffect", 1); 
                studentInfo = Container<Meqs.Logic.Interface.IStudentInfoLogic>.Instance.FindAll(table);
                if (eexam == 1)
                {
                    subjEdu = Container<Meqs.Logic.Interface.IExamSubjecyEducationLogic>.Instance.GetExamCause(examid, classType);
                    table = new Hashtable();
                    table.Add("TableName", CommonScore.GetGradeStoreTable(Grade));
                    table.Add("SchoolMark", CommonScore.GetSchoolMark);
                    table.Add("ExamID", examid);
                    table.Add("ClsID", classId);
                    gse = Container<Meqs.Logic.Interface.IGradeScoreEducationLogic>.Instance.FindAll(table);
                }
                else
                {
                    subjSchool = Container<Meqs.Logic.Interface.IExamSubjecySchoolLogic>.Instance.GetExamCause(examid, classType,CommonScore.GetSchoolMark);

                    table = new Hashtable();
                    table.Add("SchoolMark", CommonScore.GetSchoolMark);
                    table.Add("ExamID", examid);
                    table.Add("ClsID", classId);
                    eds = Container<Meqs.Logic.Interface.IExamDetailSchoolLogic>.Instance.FindAll(table);
                }

                Repeater1.DataSource = studentInfo;
                Repeater1.DataBind();

            }
        }
    }
    private string GetStudentIdList(IList<StudentInfo> sInfo)
    {
        string ids = "(0";
        foreach(StudentInfo si in sInfo)
        {
            ids += ","+si.RID;
        }
        ids += ")";
        return ids;
    }
    private string GetNextId(int subjid,int stuid,string stuCode)
    { 
        for (int index = 0; index < studentInfo.Count; index++)
        {
            if (stuid == studentInfo[index].RID && index < studentInfo.Count - 1)
            {
                return "subject" + subjid + "_" + studentInfo[index + 1].StudentCode;
            }
        }
        return "";
    }

    protected string GetTableWidth()
    {
        int w = 0;
        if (subjEdu != null)
        {
            w = 200 + subjEdu.Count * 120;
        }
        return w.ToString();
    }

    /// <summary>
    /// 获取table头
    /// </summary>
    /// 姓名 学号 考试科目
    /// <returns></returns>
    protected string GetHeader()
    {
        int w = (700 - 160);
        string header = "<th style='width:80px;text-align:left;padding-left: 5px;'>学号</th><th style='width:120px;text-align:left;padding-left: 5px;'>姓名</th>";
        if (eexam == 1)
        {
            if (subjEdu != null)
            {
                //w = (subjEdu.Count == 0 ? 0 : w / (subjEdu.Count));
                foreach (ExamSubjecyEducation2 ese in subjEdu)
                {
                    //header += "<th width='" + w + "px' style='text-align:right;padding-right: 5px;'>" + ese.SubjectName + "</th>";
                    header += "<th style='width:120px;text-align:right;padding-right: 5px;'>" + ese.SubjectName + "</th>";
                }
            }
            
        }
        else
        {
            if (subjSchool != null)
            {
                //w = (subjSchool.Count == 0 ? 0 : w / (subjSchool.Count));
                foreach (ExamSubjecySchool2 ese in subjSchool)
                {
                    header += "<th style='width:120px;text-align:right;padding-right: 5px;'>" + ese.SubjectName + "</th>";
                }
            }
        }
        return header;
    }
    //private StudentInfo GetStudentInfo(int id)
    //{
    //    foreach (StudentInfo si in studentInfo)
    //    {
    //        if (si.RID == id)
    //        {
    //            return si;
    //        }
    //    }
    //    return null;
    //}
    /// <summary>
    /// 够找一个学生的考试成绩
    /// </summary>
    /// <param name="stuid"></param>
    /// <returns></returns>
    protected string GetStudent(int stuid,string StudentCode,string StudentName)
    {
        string header = "<tr  style='width:80px;background-color: White;' id=" + stuid + " StudentCode=" + StudentCode + " StudentName= " + StudentName + " {scoreObj}>";
        string scoreObj = " stuid=" + stuid + " ";
        //int w = (700 - 160);
        header += "<td style='width:120px;text-align:left;padding-left: 5px;'>" + StudentCode + "</td><td style='text-align:left;padding-left: 5px;'>" + StudentName + "</td>";
        if (eexam == 1)
        {
            if (subjEdu != null)
            {
                //w = (subjEdu.Count == 0 ? 0 : w / (subjEdu.Count));
                foreach (ExamSubjecyEducation2 ese in subjEdu)
                {
                    
                    string score = GetTongKaoScore(stuid, ese.SubjectID);
                    scoreObj += " subject" + ese.SubjectID + "=" + score + " ";
                    //header += "<td width='" + w + "px' style='text-align:right;padding-left: 5px;padding-right: 5px;'><input type='text' name='subject" + ese.SubjectID + "' id='subject" + ese.SubjectID + "_" + StudentCode + "' maxlength='6' class='txtStyle' style='text-align: right; border-left: 0px; width:100%;border-top: 0px; border-right: 0px; border-bottom: 0px;'  value='" + (score == "null" ? "" : score) + "' oldvalue='" + (score == "null" ? "" : score) + "' onkeypress='return OnTextKeyPress(event.keyCode,this);' onpaste='return false;' ondragenter='return false;'  onfocusout='optionSettingScore(this)' onclick='modi(this)' readonly /></td>";
                    header += "<td  style='width:120px;text-align:right;padding-left: 5px;padding-right: 5px;'><input nextid='" + GetNextId(ese.SubjectID, stuid, StudentCode) + "' name='subject" + ese.SubjectID + "' id='subject" + ese.SubjectID + "_" + StudentCode + "'  maxlength='6' class='txtStyle' style='width:120px;text-align: right; border-left: 0px;border-top: 0px; border-right: 0px; border-bottom: 0px;'  value='" + (score == "null" ? "" : score) + "' oldvalue='" + (score == "null" ? "" : score) + "' onkeypress='return OnTextKeyPress(event.keyCode,this);' onpaste='return false;' ondragenter='return false;' onkeydown='movefocus(this,event,\"" + GetNextId(ese.SubjectID, stuid, StudentCode) + "\")'  onfocusout='optionSettingScore(this)' onclick='modi(this)' readonly /></td>";
                }
            }
        }
        else
        {
            if (subjSchool != null)
            {
                //w = (subjSchool.Count == 0 ? 0 : w / (subjSchool.Count));
                foreach (ExamSubjecySchool2 ese in subjSchool)
                {
                    string score = GetXiaoKaoScore(stuid, ese.SubjectID);
                    scoreObj += "subject" + ese.SubjectID + "=" + score + " ";
                    header += "<td style='width:120px;text-align:right;padding-left: 5px;padding-right: 5px;'><input nextid='" + GetNextId(ese.SubjectID, stuid, StudentCode) + "'  name='subject" + ese.SubjectID + "' id='subject" + ese.SubjectID + "_" + StudentCode + "'  maxlength='6' class='txtStyle' style='text-align: right;width:120px; border-left: 0px; border-top: 0px; border-right: 0px; border-bottom: 0px;'  value='" + (score == "null" ? "" : score) + "' oldvalue='" + (score == "null" ? "" : score) + "' onkeypress='return OnTextKeyPress(event.keyCode,this);' onpaste='return false;' ondragenter='return false;' onkeydown='movefocus(this,event,\"" + GetNextId(ese.SubjectID, stuid, StudentCode) + "\")'   onfocusout='optionSettingScore(this)' onclick='modi(this)' readonly /></td>";
                }
            }
        }
            

        header += "</tr>";
        header = header.Replace("{scoreObj}", scoreObj);
        return header;
    }

    /// <summary>
    /// 获得某学生的统考分数
    /// </summary>
    /// <param name="stuId"></param>
    /// <param name="subjId"></param>
    /// <returns></returns>
    private string GetTongKaoScore(int stuId,int subjId)
    {

        foreach (GradeScoreEducation g in gse)
        {
            if (g.StudentID == stuId && g.SubjectID == subjId)
            {
                return (g.Score == null) ? "null" : g.Score.ToString();
            }
        }
        return "null";
    }

    /// <summary>
    /// 获得某学生的校考分数
    /// </summary>
    /// <param name="stuId"></param>
    /// <param name="subjId"></param>
    /// <returns></returns>
    private string GetXiaoKaoScore(int stuId, int subjId)
    {
        foreach (ExamDetailSchool e in eds)
        {
            if (e.StudentID == stuId && e.SubjectID == subjId)
            {
                return (e.Score == null) ? "null" : e.Score.ToString();
            }
        }
        return "null";
    }

    protected void btnBind_Click(object sender, EventArgs e)
    {
        ////List<Classes> list = (List<Classes>)Container<IClassesLogic>.Instance.FindAll();

        ////List<Classes> newList = ConvertHtemlCode.ConvertClassHtmlCode(list);
        //List<MyTest> mytest = new List<MyTest>();
        //mytest.Add(new MyTest(1,"A3B56" , "刘德华"));
        //mytest.Add(new MyTest(2,"7C098" ,  "张学友"));
        //mytest.Add(new MyTest(3, "AB776" , "国护城"));
        //Repeater1.DataSource = mytest;
        //Repeater1.DataBind();
    }
    /// <summary>
    /// 保存学生分数
    /// </summary>
    /// <param name="stuids">学生id列表</param>
    /// <param name="subjectids">科目列表</param>
    /// <param name="scores">分数列表</param>
    /// <param name="emid">考试id</param>
    /// <param name="eem">是否是统考</param>
    /// <param name="clsid">班级id</param>
    /// <param name="clsType">文理分科</param>
    /// <param name="g"></param>
    /// <returns></returns>
    [WebMethod]//KindSettingsEducation[] kinds, int examid, int subjectid
    public static string SaveStudentScores(int[] stuids, int[] subjectids, double[] scores, int emid, int eem, int clsid, int clsType, int g)
    {
        //统考
        if (eem == 1)
        {
            ((IGradeScoreEducationLogic)Container<IGradeScoreEducationLogic>.Instance).SaveStudentScores(stuids, subjectids, scores, emid, clsType,clsid, CommonScore.GetGradeStoreTable(g), CommonScore.GetSchoolMark);
        }
        else
        {
            ((IExamDetailSchoolLogic)Container<IExamDetailSchoolLogic>.Instance).SaveStudentScores(stuids, subjectids, scores, emid, clsType, g, clsid, CommonScore.GetSchoolMark);
        }
        return "";
    }

    [WebMethod]//KindSettingsEducation[] kinds, int examid, int subjectid
    public static string GetExcel(string[] stunumbers,string[] stuNames, int[] subjectids,string[] subjectNames, double[] scores, int emid, int eem, int clsid, int clsType, int g)
    {
        //DownLoad(SaveFile());
        //HttpContext.Current.Response.Write("<script>window.opener=null;window.close();</script>");
        //HttpContext.Current.Response.End();
        
        //string name = SaveFile();

        string name = SaveExcel(stunumbers, stuNames, subjectids, subjectNames, scores, emid, eem, clsid, clsType, g);
        return name;
    }




    private static string SaveExcel(string[] stunumbers, string[] stuNames, int[] subjectids, string[] subjectNames, double[] scores, int emid, int eem, int clsid, int clsType, int g)
    {
        string temp_path = HttpContext.Current.Server.MapPath("xls_files");//生成的文件存放路径
        HSSFWorkbook wb = new HSSFWorkbook();
    
        ClsInfo ci = ((IClsInfoLogic)Container<IClsInfoLogic>.Instance).FindById(clsid);
        HSSFCellStyle style = wb.CreateCellStyle();
        style.BorderLeft = (short)1;
        style.BorderRight = (short)1;
        //style.BorderTop=HSSFCellStyle.BORDER_DOUBLE;
        style.FillForegroundColor = HSSFColor.GREY_25_PERCENT.index;
        style.FillPattern = HSSFCellStyle.SOLID_FOREGROUND;
        style.Alignment = HSSFCellStyle.ALIGN_CENTER;
        HSSFSheet sheet = wb.CreateSheet(ci.ClsName + "成绩导入");
        HSSFRow row = sheet.CreateRow((short)0);
        HSSFCell cell = row.CreateCell((short)0);
        cell.SetCellValue("学号");
        cell.SetCellType(1);
        cell.CellStyle = style;

        row = sheet.CreateRow((short)0);
        cell = row.CreateCell((short)1);
        cell.SetCellValue("姓名");
        cell.SetCellType(1);
        cell.CellStyle = style;
        for (int i = 0; i < subjectNames.Length; i++)
        {
            row = sheet.CreateRow((short)0);
            cell = row.CreateCell((short)(i + 2));
            cell.SetCellValue(subjectNames[i]);
            cell.SetCellType(1);
            cell.CellStyle = style;
        }

        for (int i = 0; i < stunumbers.Length;i++ )
        {
            row = sheet.CreateRow((short)(i + 1));
            cell = row.CreateCell((short)0);
            cell.SetCellValue(stunumbers[i]);
            cell.SetCellType(1);

            row = sheet.CreateRow((short)(i + 1));
            cell = row.CreateCell((short)1);
            cell.SetCellValue(stuNames[i]);
            cell.SetCellType(1);

            for (int j = 0; j<subjectids.Length; j++)
            {
                row = sheet.CreateRow((short)(i + 1));
                cell = row.CreateCell((short)(2 + j));
                cell.SetCellValue(scores[i * subjectids.Length + j] == -1 ? "" : "" + scores[i * subjectids.Length + j]);
            }
        }
            
       
        string tick = DateTime.Now.Ticks.ToString();
        string save_path = temp_path + "\\" + DateTime.Now.ToString("yy-MM-dd") + SchoolCookie.ExamName + ".xls";
        System.Web.HttpContext.Current.Session["filepath"] = DateTime.Now.ToString("yy-MM-dd") + SchoolCookie.ExamName + ".xls";
        

        FileStream file = new FileStream(save_path, FileMode.Create);
        wb.Write(file);
        file.Close();
        return DateTime.Now.ToString("yy-MM-dd") + SchoolCookie.ExamName + ".xls";
    }
    
    private static void DownLoad(string path)
    {
        if (path != null && File.Exists(path))
        {
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            //清除缓冲区流中的所有内容输出

            HttpContext.Current.Response.Clear();

            //将下载保存对话框指定默认的文件名添加到HTTP头中
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;   filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));//避免中文出现乱码现象   

            //在header中指定文件的大小，使浏览器能显示下载过程
            HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

            //设置输出流的 HTTP MIME 类型
            HttpContext.Current.Response.ContentType = "application/octet-stream";

            // 发送文件流到客户端
            HttpContext.Current.Response.WriteFile(file.FullName);
            // 停止该页的执行



        }
        else
        {
            HttpContext.Current.Response.Write("文件自动下载中断,请手动下载");
        }
    }

}

